import Worker from './Worker';

/**
 * 创建线程池
 * @param module require方法返回的module
 * @return {function(*):(*)} 在线程池中执行的方法, 接收在.worker.js文件中导出的方法
 */
function Pool(module){
	const count=navigator.hardwareConcurrency||4;
	const queue=[];
	const waitWorkers=[];
	for(let i=0;i<count;++i){
		const worker=Worker(module);
		worker.completed=function(){
			if(queue.length){
				const {resolve,task}=queue.pop();
				resolve(this.then(function(obj){
					return task(obj);
				}));
			}else{
				waitWorkers.push(worker);
			}
		};
		waitWorkers.push(worker);
	}
	return function(task){
		if(waitWorkers.length){
			return waitWorkers.pop().then(function(obj){
				return task(obj);
			});
		}else{
			return new Promise(function(resolve){
				queue.push({
					resolve,
					task,
				});
			});
		}
	};
}

export default Pool;
